package com.kfm.web.controller.system;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kfm.common.domain.entity.Orders;
import com.kfm.common.domain.response.Result;
import com.kfm.common.util.Common;
import com.kfm.order.service.OrdersService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/order")
public class SysOrderController {

    @Resource
    private OrdersService ordersService;

    @RequestMapping("/list")
    @PreAuthorize("hasAuthority('order:list') or hasAnyRole('ROLE_admin')")
    public Result list() {
        // 查询所有订单信息
        List<Orders> list = ordersService.selectAll();
        return list == null ? Result.failure("没有查询到订单") : Result.success("查询成功", list);
    }

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('order:list') or hasAnyRole('ROLE_admin')")
    public Result list(@RequestBody String body) {
        JSONObject entries = JSONUtil.parseObj(body);
        Map<String, String> condition = new HashMap<>(); // 构建查询的条件
        // 获取查询的结束时间和开始时间
        JSONArray dates = entries.getJSONArray("date");
        String id = entries.getStr("id");
        String username = entries.getStr("memberName");
        if (!ObjectUtils.isEmpty(id)) {
            condition.put("id", id);
        }
        if (!ObjectUtils.isEmpty(username)) {
            condition.put("username", username);
        }
        if (!ObjectUtils.isEmpty(dates)) {
            condition.put("start", Common.formatterDate(dates.getDate(0)));
            condition.put("end", Common.formatterDate(dates.getDate(1)));
        }
        // 查询所有订单信息
        List<Orders> list = ordersService.selectByCondition(condition);
        return list.isEmpty() ? Result.failure("没有查询到订单") : Result.success("查询成功", list);
    }

    @PostMapping("/edit")
    @PreAuthorize("hasAuthority('order:edit') or hasAnyRole('ROLE_admin')")
    public Result edit(@RequestBody Orders orders) {
        int result = ordersService.updateByPrimaryKeySelective(orders);
        return result == 0 ? Result.failure("修改失败") : Result.success("修改成功");
    }


    @GetMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('order:delete') or hasAnyRole('ROLE_admin')")
    public Result remove(@PathVariable("id") String id) {
        int result = ordersService.deleteByPrimaryKey(id);
        return result == 0 ? Result.failure("删除失败") : Result.success("删除成功");
    }
}
